library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
library(showtext)

# Define updated region list and custom facet labels
c_list_agg <- c(
  "East Asia & Pacific (excluding high income)", 
  "Europe & Central Asia (excluding high income)", 
  "Latin America & Caribbean (excluding high income)", 
  "Middle East & North Africa (excluding high income)", 
  "South Asia (excluding high income)", 
  "Sub-Saharan Africa (excluding high income)"
)

legend_labels <- c(
  "East Asia & Pacific (excluding high income)" = "East Asia and Pacific",
  "Europe & Central Asia (excluding high income)" = "Europe and Central Asia",
  "Latin America & Caribbean (excluding high income)" = "Latin America and\nthe Caribbean", 
  "Middle East & North Africa (excluding high income)" = "Middle East and North Africa", 
  "South Asia (excluding high income)" = "South Asia", 
  "Sub-Saharan Africa (excluding high income)" = "Sub-Saharan Africa"
)

# Prepare the data
sav_interest_MM_data <- data %>%
  filter(group == "all") %>%
  filter(year == 2024) %>%
  filter(countrynewwb %in% c_list_agg) %>%
  select(countrynewwb, ts_savfor_fi_mm, ts_savfor_fi, ts_savfor_mm, 
         fin_interest_fi_mm, fin_interest_fi, fin_interest_mm_o) %>%
  pivot_longer(cols = c(ts_savfor_fi_mm, ts_savfor_fi, ts_savfor_mm),
               names_to = "bar_type", values_to = "total_save") %>%
  mutate(
    interest = case_when(
      bar_type == "ts_savfor_fi_mm" ~ fin_interest_fi_mm,
      bar_type == "ts_savfor_fi" ~ fin_interest_fi,
      bar_type == "ts_savfor_mm" ~ fin_interest_mm_o,
      TRUE ~ NA_real_
    ),
    no_interest = total_save - interest
  ) %>%
  pivot_longer(cols = c(interest, no_interest),
               names_to = "group", values_to = "value") %>%
  mutate(
    total_save = total_save * 100,
    value = value * 100,
    group = recode(group,
                   "interest" = "Saved formally and received interest",
                   "no_interest" = "Saved formally and did not receive interest"),
    group = factor(group, levels = c("Saved formally and did not receive interest",
                                     "Saved formally and received interest")),
    bar_type = factor(bar_type, 
                      levels = c("ts_savfor_fi_mm", "ts_savfor_fi", "ts_savfor_mm"),
                      labels = c("Saved\nformally",
                                 "Saved formally\nusing a bank\nor similar financial\ninstitution\naccount",
                                 "Saved\nusing\nmobile\nmoney")),
    countrynewwb = factor(countrynewwb, levels = c_list_agg)
  ) %>%
  # ??? KEEP ONLY 'Saved formally'
  filter(bar_type == "Saved\nformally")

# Plot
p <- ggplot(sav_interest_MM_data, aes(x = bar_type, y = value, fill = group)) +
  geom_bar(stat = "identity", position = "stack", width = 0.6, color = "black", size = 0.5) +
  facet_wrap(
    ~countrynewwb,
    nrow = 1,
    strip.position = "bottom",
    labeller = labeller(countrynewwb = legend_labels)
  ) +
  scale_fill_manual(
    values = c(
      "Saved formally and did not receive interest" = "#5696D0",
      "Saved formally and received interest" = "#0F72BC"
    )
  ) +
  scale_y_continuous(
    limits = c(0, 70),
    breaks = seq(0, 100, by = 20),
    labels = function(x) paste0(x)
  ) +
  theme_minimal(base_family = "Nunito Sans") +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    strip.text = element_text(size = 18, color = "black"),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_blank(),   # ??? Remove x-axis labels
    axis.text.y = element_text(size = 18, color = "black"),
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.text = element_text(size = 18),
    plot.title = element_text(size = 26, face = "bold", hjust = 0),
    plot.subtitle = element_text(size = 22, hjust = 0),
    plot.caption = element_text(size = 18, hjust = 0, color = "black")  # ??? Left-aligned caption
  ) +
  labs(
    title = "In most regions, around 10 percent of adults saved formally and received interest for their savings",
    subtitle = "Adults saving at a bank or similar financial institution or using a mobile money account in the past year (%), 2024",
    caption = "Source: Global Findex Database"  # ??? Caption added
  ) +
  guides(fill = guide_legend(nrow = 2, byrow = TRUE))

# Show plot
p

# Save plot
ggsave(
  filename = file.path(folder_path, "3.1.6.png"),
  plot = p,
  width = 20,
  height = 8,
  units = "in",
  device = 'png',
  dpi = 120
)
